package com.zxshhy.mqconfirmback;

import com.alibaba.fastjson.JSONObject;
import com.zxshhy.entity.OrderStatus;
import com.zxshhy.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author: zxs
 * @Date: 2018/11/7
 * @Description:
 */

@Slf4j
@Component
public class ConfirmCallback implements RabbitTemplate.ConfirmCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrderMapper orderMapper;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("发送消息到MQ是否成功确认信息：correlationData：{};ack:{},cause:{}",correlationData,ack,cause);
        if (ack){
            log.info("发送消息到MQ成功了");
            String sendSuccessMessage = correlationData.getId();
            JSONObject jsonObject = JSONObject.parseObject(sendSuccessMessage);
            Long orderId = jsonObject.getLong("id");
            //更新订单
            Integer updateOrderRecord = orderMapper.updateOrderStatus(orderId, OrderStatus.SUCCESS.getValue());
            log.info("通过[id={}]更新订单状态[{}]: {}", orderId, OrderStatus.SUCCESS.name(),updateOrderRecord > 0 ? "成功" : "失败");
        }else {
            log.info("发送消息到MQ失败了,消息：{},case:{}",correlationData.getId(),cause);
        }
    }
}
